#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>

unsigned char buffer[640+16];
void main(void)
{
    struct sockaddr_in local_addr, remote_addr;
    int result;
    int socklen;
    int i;
    int fdsocket = socket(AF_INET, SOCK_DGRAM, 0);

    if (fdsocket == -1) 
    {
      perror("socket()");
      //exit(1);
    }

    //printf("bind port = %d, 数据接收开始\n", *((int*)p));
    /* 设置远程连接的信息*/
    local_addr.sin_family = AF_INET;                 /* 注意主机字节顺序*/
    local_addr.sin_port = htons(20000);          /* 远程连接端口, 注意网络字节顺序*/
    local_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* 远程 IP 地址, inet_addr() 会返回网络字节顺序*/
    memset(&(local_addr.sin_zero), 8, 0);                /* 其余结构须置 0*/    
    //i = *((int*)p) - UDP_BIND_PORT_START;
    bind(fdsocket, (struct sockaddr*)&local_addr, sizeof(struct sockaddr));

    //printf("数据接收开始\n");
    while(1)
    {
        //if(n > 3)
        {      
	    //if(-1 == sendto(fdsocket, pReadHeader->buffer, sizeof(pReadHeader->buffer), 0, (struct sockaddr*)&dest_addr, sizeof(struct sockaddr)))
	    socklen = sizeof(struct sockaddr);
	    result = recvfrom(fdsocket, buffer, sizeof(buffer), 0, (struct sockaddr*)&remote_addr, &socklen);
	    if(result == -1)
	    {
		    perror("数据接收");
	    }
	    else
	    {
            printf("FrameNO=%d\n", *((int*)buffer));
            //pthread_mutex_lock(&mutex_lock);
#if 0
            printf("recv sec; %ld,",    ((pk_hdr_t*)(pWriteHdrRecv[i]->buffer))->sec) ;
            printf("usec; %ld,last_play_time.sec=%ld,usec=%ld ", ((pk_hdr_t*)(pWriteHdrRecv[i]->buffer))->usec,
                last_play_time.tv_sec, last_play_time.tv_usec);
            
            val = (((pk_hdr_t*)(pWriteHdrRecv[i]->buffer))->sec  - last_play_time.tv_sec)*1000 
                + (((pk_hdr_t*)(pWriteHdrRecv[i]->buffer))->usec - last_play_time.tv_usec)/1000;
            printf("val=%d\n", val);
#endif
            //last_recv_time.tv_sec  = ((pk_hdr_t*)(pWriteHdrRecv[i]->buffer))->sec;
            //last_recv_time.tv_usec = ((pk_hdr_t*)(pWriteHdrRecv[i]->buffer))->usec;
            //((pk_hdr_t*)(pWriteHdrRecv[i]->buffer))->valid = 1;//数据包失效
            //traceprintf("共接收%d数据包\n", packagesum++);
            //sem_post(&sem_recv);
            //((pk_hdr_t*)(pWriteHeader->buffer))->sec = tv.tv_sec;
            //((pk_hdr_t*)(pWriteHeader->buffer))->usec = tv.tv_usec;

            //gettimeofday (&tv , &tz);
            //printf("send tv_sec; %llx ",    tv.tv_sec) ;
            //printf("tv_usec; %llx \n", tv.tv_usec);
#if DEBUG_SAVE_RECV_PCM
            fwrite(pWriteHdrRecv[i]->buffer, sizeof(pWriteHdrRecv[i]->buffer), 1, fp);
#endif        
		    //traceprintf("收到数据 %d byte, n=%d\n", result, n+1);
		    //pWriteHdrRecv[i] = pWriteHdrRecv[i]->pNext;
		    //package_count[i]++;
            //pthread_mutex_unlock(&mutex_lock);
	    }
	    }
    }
}
